/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年6月17日
 * @version 0.1
 */
package com.suredy.base.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.base.model.Action;
import com.suredy.base.model.Permission;
import com.suredy.base.model.Resource;
import com.suredy.base.model.Role;
import com.suredy.base.model.Role2Permission;
import com.suredy.base.model.User;
import com.suredy.base.model.User2Permission;
import com.suredy.base.service.PermissionSrv;
import com.suredy.base.service.ResourceSrv;
import com.suredy.base.service.Role2PermissionSrv;
import com.suredy.base.service.RoleSrv;
import com.suredy.base.service.User2PermissionSrv;
import com.suredy.base.service.UserSrv;
import com.suredy.core.ctrl.BaseCtrl;

/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value = "config")
public class PermissionCtrl extends BaseCtrl {

	private final static Logger log = LoggerFactory.getLogger(PermissionCtrl.class);
	@Autowired
	private ResourceSrv resourceSrv;

	@Autowired
	private PermissionSrv ps;

	@Autowired
	private Role2PermissionSrv r2ps;

	@Autowired
	private RoleSrv roleSrv;
	
	@Autowired
	private UserSrv userSrv;
	
	@Autowired
	private User2PermissionSrv u2ps;

	/**
	 * get permission list
	 * 
	 * @param type
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "role2permission-list")
	public ModelAndView getPermissions() {
		ModelAndView view = new ModelAndView("config/role2permission-list");
		List<Role2Permission> data = this.r2ps.getAll();
		view.addObject("data", data);
		return view;
	}

	@RequestMapping(value = "resource2role")
	public ModelAndView Resource2Role(String resourceId) {
		ModelAndView view = new ModelAndView("config/resource2role");

		List<Role> roles = this.roleSrv.getAll();

		Resource resource = this.resourceSrv.getById(resourceId);

		List<Permission> permissions = this.ps.getById(resourceId);
		List<Role2Permission> rolePermissions = new ArrayList<Role2Permission>();
		for (Permission p : permissions) {
			List<Role2Permission> temp = this.r2ps.getByPermission(p.getId());
			rolePermissions.addAll(temp);
		}
		
		view.addObject("resource", resource);
		view.addObject("roles", roles);
		view.addObject("permissions", permissions);
		view.addObject("actions", Action.values());
		view.addObject("rolePermissions", rolePermissions);
		return view;
	}
	
	@Transactional
	@RequestMapping("resource2role-save")
	@ResponseBody
	public String Resource2RoleSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		String url = request.getParameter("url");
		if (StringUtils.isBlank(id) || StringUtils.isBlank(url)) {
			log.error("Parameter String[id/url] is blank.");
			return "0";
		}
		
		for (Action action : Action.values()) {
			//添加权限
			Permission permission = this.ps.GetOrCreate(id, url, action.getAction());

			//删除全部role2permission引用
			List<Role2Permission> rolePermissions = this.r2ps.getByPermission(permission.getId());
			for (Role2Permission rp : rolePermissions) {
				this.r2ps.delete(rp);
			}
			
			//加入新的role2permission引用
			String[] roleIds = request.getParameterValues(action.toString());
			if (roleIds != null && roleIds.length > 0) {
				for (String roleId : roleIds) {
					Role2Permission rp = new Role2Permission();
					rp.setRolePermission(permission);
					rp.setRoleId(roleId);
					this.r2ps.save(rp);
				} 
			}
		}

		return "1";
	}
	
	@RequestMapping(value = "role2resource")
	public ModelAndView Role2Resource(String roleId) {
		ModelAndView view = new ModelAndView("config/role2resource");
		
		List<Resource> resources = this.resourceSrv.getAll();
		Role role = this.roleSrv.getById(roleId);
		List<Role2Permission> rolePermissions = this.r2ps.getByRole(roleId);
		List<Permission> permissions = new ArrayList<Permission>();		
		for (Resource resource : resources) {
			List<Permission> temp = this.ps.getById(resource.getId());
			permissions.addAll(temp);
		}
				
		view.addObject("resources", resources);
		view.addObject("role", role);
		view.addObject("permissions", permissions);
		view.addObject("actions", Action.values());
		view.addObject("rolePermissions", rolePermissions);
		return view;

	}
	
	@Transactional
	@RequestMapping("role2resource-save")
	@ResponseBody
	public String Role2ResourceSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return "0";
		}
		
		//删除全部role2permission引用
		List<Role2Permission> rolePermissions = this.r2ps.getByRole(id);
		for (Role2Permission rp : rolePermissions) {
			this.r2ps.delete(rp);
		}
		
		for (Action action : Action.values()) {			
			//新的role2permission引用
			String[] resourceIds = request.getParameterValues(action.toString());
			if (resourceIds != null && resourceIds.length > 0) {
				for (String resourceId : resourceIds) {
					Resource resource = this.resourceSrv.getById(resourceId);
					Permission permission = this.ps.GetOrCreate(resourceId, resource.getUri(), action.getAction());
					Role2Permission rp = new Role2Permission();
					rp.setRolePermission(permission);
					rp.setRoleId(id);
					this.r2ps.save(rp);
				} 
			}
		}

		return "1";
	}
	
	@RequestMapping(value = "user2resource")
	public ModelAndView User2Resource(String userId) {
		ModelAndView view = new ModelAndView("config/user2resource");
		
		List<Resource> resources = this.resourceSrv.getAll();
		User user = this.userSrv.getById(userId);
		List<User2Permission> userPermissions = this.u2ps.getByUser(userId);
		List<Permission> permissions = new ArrayList<Permission>();		
		for (Resource resource : resources) {
			List<Permission> temp = this.ps.getById(resource.getId());
			permissions.addAll(temp);
		}
				
		view.addObject("resources", resources);
		view.addObject("user", user);
		view.addObject("permissions", permissions);
		view.addObject("actions", Action.values());
		view.addObject("userPermissions", userPermissions);
		return view;

	}
	
	@Transactional
	@RequestMapping("user2resource-save")
	@ResponseBody
	public String User2ResourceSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return "0";
		}
		
		//删除全部role2permission引用
		List<User2Permission> userPermissions = this.u2ps.getByUser(id);
		for (User2Permission rp : userPermissions) {
			this.u2ps.delete(rp);
		}
		
		for (Action action : Action.values()) {			
			//新的user2permission引用
			String[] resourceIds = request.getParameterValues(action.toString());
			if (resourceIds != null && resourceIds.length > 0) {
				for (String resourceId : resourceIds) {
					Resource resource = this.resourceSrv.getById(resourceId);
					Permission permission = this.ps.GetOrCreate(resourceId, resource.getUri(), action.getAction());
					User2Permission up = new User2Permission();
					up.setUserPermission(permission);
					up.setUserId(id);
					this.u2ps.save(up);
				} 
			}
		}

		return "1";
	}
}
